package com.demo.fulllink.service.impl;

import com.demo.fulllink.common.emum.ResponseErrorEnum;
import com.demo.fulllink.module.po.AccountPO;
import com.demo.fulllink.module.vo.NotifyVO;
import com.demo.fulllink.module.vo.OrderVO;
import com.demo.fulllink.module.vo.ResponseVO;
import com.demo.fulllink.service.NotifyService;
import com.demo.fulllink.service.SmsNotifyService;
import com.demo.fulllink.service.StorageAccountService;
import com.demo.fulllink.service.StorageNotifyService;
import com.demo.wormhole.component.mock.exception.WormholeMockRuntimeExpetion;
import com.demo.wormhole.core.context.WormholeContextHolder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class NotifyServiceImpl implements NotifyService {
    
    @Autowired
    private StorageNotifyService storageNotifyService;
    
    @Autowired
    private StorageAccountService storageAccountService;
    
    @Autowired
    private SmsNotifyService smsNotifyService;
    
    private Logger logger = LoggerFactory.getLogger(NotifyServiceImpl.class);
    
    @Override
    public ResponseVO notifyHandel(OrderVO orderVO) {
        AccountPO accountPO = storageAccountService.findByID(orderVO.getAccountId());
        if (null != accountPO) {
            NotifyVO notifyVO = toNotifyVO(orderVO);
            notifyVO.setAccountName(accountPO.getUsername());
            try {
                smsNotifyService.send(notifyVO);
                notifyVO.setStatus(1);
            } catch (WormholeMockRuntimeExpetion e) {
                logger.error(e.getMessage());
                notifyVO.setStatus(0);
            }
            return storageNotifyService.insert(notifyVO);
        }
        return ResponseErrorEnum.ACCOUNT_NOT_EXIST_ERROR.toResponseVO();
    }
    
    private NotifyVO toNotifyVO(OrderVO orderVO) {
        NotifyVO notifyVO = new NotifyVO();
        notifyVO.setType(1);
        notifyVO.setOrderId(orderVO.getId());
        notifyVO.setStatus(1);
        notifyVO.setToken(WormholeContextHolder.getProperty(null));
        notifyVO.setCreateDate(new Date());
        return notifyVO;
    }
}
